package com.liyunc.demo.service.impl;

import com.liyunc.demo.model.entity.GoodsEntity;
import com.liyunc.demo.model.entity.OrderEntity;
import com.liyunc.demo.model.repository.GoodsRepository;
import com.liyunc.demo.utils.IdWorker;
import com.liyunc.demo.utils.OrderRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class OrderCreateThread implements Runnable {
    @Autowired
    private CacheServiceImpl cacheService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private GoodsRepository goodsRepository;

    @Override
    public void run() {
        LinkedBlockingQueue<OrderRecord> orderRecords = cacheService.orderRecords;
        OrderRecord orderRecord = orderRecords.peek();
        if (orderRecord != null) {
            GoodsEntity goods = cacheService.findOne(orderRecord.getGoodsId());
            //4.生成秒杀订单，将订单保存到redis中
            OrderEntity seckillOrder = new OrderEntity();
            seckillOrder.setUserId(orderRecord.getUserId());
            seckillOrder.setSellerId(goods.getSellerId());
            seckillOrder.setSeckillId(idWorker.nextId());
            seckillOrder.setMoney(goods.getCostPrice());
            seckillOrder.setCreateTime(new Date());
            seckillOrder.setStatus("0");
            //设置同步代码块
            synchronized (OrderCreateThread.class) {
                //保证每次拿的都是最新的信息，重新获取对象
                goods = cacheService.findOne(orderRecord.getGoodsId());
                //5.秒杀商品库存-1
                goods.setStockCount(goods.getStockCount() - 1);
                //6.判断库存量是否<=0
                if (goods.getStockCount() <= 0) {
                    //7.是，将秒杀商品更新到数据库，删除秒杀商品缓存
                    goodsRepository.saveAndFlush(goods);
                        cacheService.delete(orderRecord.getGoodsId());
                } else {
                    //8.否，将秒杀商品更新到数据库
                    goodsRepository.saveAndFlush(goods);
                }
            }
        }
    }
}
